// js/members.js

// 加载成员列表
function loadMembers() {
    fetch('/api/team/members')
        .then(response => response.json())
        .then(members => {
            const memberListElem = document.getElementById("memberList");
            memberListElem.innerHTML = '';
            members.forEach(member => {
                const row = document.createElement("tr");
                row.innerHTML = `
                    <td>${member.username}</td>
                    <td>${member.password}</td>
                    <td>${member.name}</td>
                    <td>${member.note}</td>
                    <td>
                        <button onclick="deleteMember('${member.username}')">删除</button>
                        <button onclick="updateMember('${member.username}')">更新</button>
                    </td>
                `;
                memberListElem.appendChild(row);
            });
        })
        .catch(error => console.error("加载成员失败:", error));
}

// 添加成员
function addMember(event) {
    event.preventDefault();

    const newMember = {
        username: document.getElementById("newUsername").value,
        password: document.getElementById("newPassword").value,
        name: document.getElementById("newName").value,
        note: document.getElementById("note").value,
    };

    fetch('/api/team/add', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(newMember)
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert("添加成功！");
                loadMembers();
                document.getElementById("addMemberForm").reset();
            } else {
                alert("添加失败：" + data.message);
            }
        })
        .catch(error => console.error("添加成员错误:", error));
}

// 删除成员
function deleteMember(username) {
    fetch(`/api/team/delete/${username}`, {
        method: 'DELETE'
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert("删除成功！");
                loadMembers();
            } else {
                alert("删除失败：" + data.message);
            }
        })
        .catch(error => console.error("删除成员错误:", error));
}

// 更新成员
function updateMember(username) {
    const newName = prompt("请输入新的姓名：");
    const newPassword = prompt("请输入新的密码：");
    const newNote = prompt("请输入新的备注");
    const updatedMember = {
        username: username,
        password: newPassword,
        name: newName,
        note: newNote,
    };

    fetch('/api/team/update', {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(updatedMember)
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                alert("更新成功！");
                loadMembers();
            } else {
                alert("更新失败：" + data.message);
            }
        })
        .catch(error => console.error("更新成员错误:", error));
}

async function getMemberByUsername() {
    // 获取页面中的相关元素
    const usernameInput = document.getElementById('usernameInput');
    const resultDiv = document.getElementById('result');

// 给确认按钮添加点击事件监听器

    const username = usernameInput.value;
    // 简单验证用户名是否为空
    if (username === '') {
        alert('请输入用户名');
        return;
    }
    try {
        // 使用fetch方法发送请求，假设后端接口地址是/api/user，实际需替换为真实后端接口
        await fetch(`api/team/getMember?username=${username}`, {
            method: 'GET',
        }).then(response => response.json())
            .then(member => {
                if (member.username) {
                    resultDiv.innerHTML =
                        `<h4>查询结果：</h4>
                      <h4>姓名：${member.name}</h4>
                     <h4>用户名：${member.username}</h4>
                    <h4>学号（密码）：${member.password}</h4>
                     <h4>备注：${member.note}</h4>
            `;
                } else {
                    resultDiv.innerHTML = "没有该用户捏"
                }

            }).catch(err => {
                resultDiv.innerHTML = '查询出现错误，状态码：' + err.statusText;
            })
    } catch (error) {
        resultDiv.innerHTML = '请求出现异常：' + error.message;
    }

}
